#include "app_sys.h"

volatile unsigned int app_sys_ticks = 0x00;

unsigned int app_sys_crc32_cal(unsigned int buff[], unsigned int length)
{
    LL_CRC_ResetCRCCalculationUnit(CRC);
    for (unsigned int i = 0U; i < length; i++)
    {
        LL_CRC_FeedData32(CRC, buff[i]);
    }
    /* Return CRC value */
    return (LL_CRC_ReadData32(CRC));
}

unsigned char time_after(unsigned int current, unsigned int expire)
{
    int32_t int32tCurrent = (int32_t)current;
    int32_t int32tExpire = (int32_t)expire;

    if (int32tCurrent > int32tExpire) {
        return 1;
    }
    
    return 0;
}

unsigned char time_before(unsigned int current, unsigned int expire)
{
    unsigned char result = time_after(current, expire);
    if (result) {
        return 0;
    }
    return 1;
}

unsigned short hex_data_to_hexstr(const unsigned char *data, unsigned short data_length, char *dst)
{
    unsigned short i = 0;
    unsigned short j = 0;

    for (i = 0; i < data_length; i++) {
        unsigned char byte = data[i];
        unsigned char high_nibble = (byte >> 4) & 0x0F;
        unsigned char low_nibble = byte & 0x0F;

        if (high_nibble < 10) {
            dst[j++] = high_nibble + '0';
        } else {
            dst[j++] = high_nibble - 10 + 'A';
        }

        if (low_nibble < 10) {
            dst[j++] = low_nibble + '0';
        } else {
            dst[j++] = low_nibble - 10 + 'A';
        }
    }

    return j;
}

unsigned short int_value_to_intstr(int value, char dst[])
{
    unsigned char is_negative = 0;
    unsigned char i = 0;
    char buffer[12];

    if (value < 0) {
        is_negative = 1;
        value = -value;
    }

    do {
        buffer[i++] = value % 10 + '0';
    } while (value /= 10);

    if (is_negative) {
        buffer[i++] = '-';
    }

    unsigned char j = 0;
    while (i > 0) {
        dst[j++] = buffer[--i];
    }
    return j;
}
